package cn.me.alphamq.nameserver.handler.cluster.chain;

import cn.me.alphamq.common.enumeration.EventCodeEnum;
import cn.me.alphamq.common.event.model.Event;
import cn.me.alphamq.common.msg.TcpMsg;
import cn.me.alphamq.common.event.EventBus;
import cn.me.alphamq.nameserver.event.model.cluster.ReplicationAckEvent;
import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 链式复制中非尾节点在客户端的 TcpMsg 处理器，可以被所有线程共享
 * <p>
 * 用于给下一个节点写入数据
 *
 * @author f
 */
@ChannelHandler.Sharable
public class NodeReplicationClientHandler extends SimpleChannelInboundHandler<TcpMsg> {

    /**
     * 事件总线
     */
    private final EventBus eventBus;

    public NodeReplicationClientHandler(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TcpMsg tcpMsg) throws Exception {
        // 根据 code 的不同，将 body 解析成不同的 Event 对象
        int code = tcpMsg.getCode();
        byte[] body = tcpMsg.getBody();
        Event event = null;

        if (EventCodeEnum.NODE_REPLICATION_ACK_REQ.getCode() == code) {
            event = JSON.parseObject(body, ReplicationAckEvent.class);
        }

        // 给事件绑定 ctx 对象
        event.setCtx(ctx);

        // 发布事件
        eventBus.publish(event);
    }
}
